<template>
  <DraggableModal :visible="props.showModal" :title="`${props.title}设备`" :maskClosable="true" @ok="modalOkFn" @cancel="modalCancelFn">
    <Form ref="formRef" :model="state.data" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
      <a-form-item label="设备名称" name="name">
        <Input v-model:value="state.data.name" />
      </a-form-item>

      <a-form-item label="设备序列号" name="sn">
        <Input v-model:value="state.data.sn" />
      </a-form-item>

      <a-form-item label="设备类型" name="type">
        <Select v-model:value="state.data.type" :options="deviceType" />
      </a-form-item>

      <a-form-item label="绑定冰箱" name="iceboxId" v-if="state.data.type === 33">
        <div style="display: flex">
          <Select v-model:value="state.data.iceboxId" :disabled="state.bindingStatus" allowClear :options="state.refrigeratorList" />
          <Button
            v-if="props.title === '修改'"
            style="margin-left: 20px"
            type="primary"
            :disabled="!state.bindingStatus && !state.data.iceboxId"
            :loading="state.bindingBtnLoading"
            @click="changeRefrigeratorBindingFn"
          >
            {{ state.bindingStatus ? '解除绑定' : '绑定冰箱' }}
          </Button>
        </div>
      </a-form-item>
    </Form>
  </DraggableModal>
</template>

<script setup lang="ts">
import { DraggableModal } from '@/framework/components/core/draggable-modal';
import { message, Form, Input, Select } from 'ant-design-vue';
import { reactive, ref, watch } from 'vue';
import Button from '@/framework/components/basic/button/button.vue';
import { storageSearch } from '@/api/base/storage_data';
import { tabletBindTabletIcebox, tabletUnbindTabletIcebox } from '@/modules/platform-management/api';
import { deviceAdd, deviceUpdate } from '@/api/base/device-data';
import { deviceType } from '../columns';

/**
 * const
 */
const props = withDefaults(
  defineProps<{
    showModal?: boolean;
    data: any;
    title: string;
  }>(),
  {
    showModal: false,
  },
);
watch(
  () => props.showModal,
  async () => {
    if (props.showModal) {
      console.log(props.data, 1111111111);
      state.data = props.data;
      state.bindingStatus = props.data?.iceboxId ? true : false;
    }
  },
);
const emits = defineEmits<{
  (e: 'update:showModal', state: boolean): void;
  (e: 'editModalOk'): void;
}>();
const formRef = ref();

/**
 * data
 */
const state: {
  data: any;
  refrigeratorList: any[];
  bindingStatus: boolean;
  bindingBtnLoading: boolean;
} = reactive({
  data: {},
  refrigeratorList: [],
  bindingStatus: false,
  bindingBtnLoading: false,
});
const rules = {
  name: [{ required: true, message: '数据必填!' }],
  sn: [{ required: true, message: '数据必填!' }],
  type: [{ required: true, message: '数据必填!' }],
};
/**
 * 冰箱数据
 */
const getRefrigeratorListFn = async () => {
  let params = {
    type: 2,
    pageSize: 1000000,
    paging: true,
    orderBy: [{ field: 'serial' }],
  };
  const res = await storageSearch(params);
  state.refrigeratorList = res.result.data.map((item) => ({
    label: item.label,
    value: item.id,
  }));
};
getRefrigeratorListFn();
/**
 * fn
 */
const modalOkFn = async () => {
  // 验证
  try {
    await formRef.value?.validateFields();
  } catch {
    return;
  }
  // 基础参数
  let params: any = {
    name: state.data.name,
    type: state.data.type,
    sn: state.data.sn,
  };
  if (props.title === '新增') {
    // 新增
    params = {
      ...params,
      organizationId: '001',
      tenantId: '001',
      data: '',
    };
    let res = await deviceAdd(params);
    if (state.data.iceboxId) {
      let subParams = {
        iceboxId: state.data.iceboxId,
        tabletIds: [res.result],
      };
      await tabletBindTabletIcebox(subParams);
    }
  } else {
    // 修改
    params = {
      ...params,
      id: state.data.id,
    };
    await deviceUpdate(params);
  }
  message.success('操作成功！');
  emits('editModalOk');
  modalCancelFn();
};
const modalCancelFn = () => {
  formRef.value?.clearValidate();
  state.data = {};
  emits('update:showModal', false);
};

const changeRefrigeratorBindingFn = async () => {
  state.bindingBtnLoading = true;
  let params: any = {};
  if (state.data.iceboxId && !state.bindingStatus) {
    params = {
      iceboxId: state.data.iceboxId,
      tabletIds: [state.data.id],
    };
    await tabletBindTabletIcebox(params);
  } else {
    params = {
      tabletId: state.data.id,
    };
    await tabletUnbindTabletIcebox(params);
  }
  message.success('操作成功！');
  emits('editModalOk');
  state.bindingBtnLoading = false;
  modalCancelFn();
};
</script>

<style scoped></style>
